<template>
	<view :class="{'weui-bottom-page':!options.noButton}">
		<view v-if="options.columns" :class="formClass" style="margin-top:0px;">
			<view class="weui-cell" :class="{'weui-cell_access': item.type=='date' || item.type=='select'}" :key="index"
				v-for="(item,index) in options.columns"
				v-if="!item.noShow && (item.editType==undefined || item.editType==formType)"
				:style="{'align-items': (item.type=='textarea' ? 'normal':'center')}">
				<view class="weui-cell__hd" v-if="options.formType!='v' && options.showDot" style="margin-right:2px;">
					<text class="weui-label" v-if="item.noCheck" style="width:10px;"></text>
					<text class="weui-label" v-else
						style="color:red;width:10px;font-size:10px;padding-top:5px;">*</text>
				</view>
				<view class="weui-cell__hd" v-if="item.type!='editor' && item.text!=undefined">
					<text class="weui-label">{{item.text}}</text>
				</view>

				<view class="weui-cell__bd weui-cell__primary" v-if="options.formType=='v'"
					:class="{'v-textarea': (item.type=='textarea' ? true:false)}">
					<view v-if="item.type=='radio'">{{getText(item)}}</view>
					<view v-else-if="item.type=='select'">
						{{item.selectText}}
					</view>
					<view v-else-if="item.type=='editor'">
						<rich-text :nodes="item.value"></rich-text>
					</view>
					<view v-else>
						{{item.value}}
					</view>
				</view>
				<view class="weui-cell__bd weui-cell__primary" v-else>
					<radio-group v-if="item.type=='radio'" :id="item.name" @change="radioChange($event,item)">
						<input type="hidden" v-model="item.value" style="display:none;" />
						<label :id="item.name + '_' + radioItem.value" :key="radioIndex" class="radio"
							v-for="(radioItem, radioIndex) in item.items">
							<radio :value="radioItem.value+''" :checked="(radioItem.value+'') === (item.value+'')" />
							{{radioItem.text}}
						</label>
					</radio-group>
					<picker v-else-if="item.type=='select'" @change="selectChange($event,item,index)" 
						:value="item.items ? item.selectIndex : item.selectText" :mode="item.mode" :fields="item.fields"
						:range="item.items" range-key="text">
						<input class="weui-input uni-input-input" :placeholder="'选择' + item.text"
							v-model="item.selectText" disabled="true"  @click="clickPicker(item,index)"/>
					</picker>
					<view v-else-if="item.type=='text'">
						<text style="padding-right:10px;">{{item.value}}</text>
						<text v-if="item.value && item.value!='' && item.msg!=undefined">({{item.msg}})</text>
					</view>
					<view v-else-if="item.type=='date'">
						<input class="weui-input uni-input-input" :placeholder="'选择' + item.text" v-model="item.value"
							@click="wPickerShow(item)" disabled="true" />
						<wPicker mode="date" :startYear="item.picker.startYear" :endYear="item.picker.endYear"
							:currentDate="item.value" :current="true" :ref="'wPicker_'+ item.name" themeColor="#f00"
							:showPicker="item.showPicker" @confirm="wPickerChange"></wPicker>
					</view>
					<view v-else-if="item.type=='address'">
						<input class="weui-input uni-input-input" placeholder="请选择城市" :value="item.area" disabled="true"
							@click="wPickerShow(item)" />
						<view class="weui-line" style="margin-top:20upx;margin-bottom:40upx;"></view>
						<input class="weui-input uni-input-input" placeholder="请输入街道及门牌" v-model="item.value"
							:maxlength="item.maxlength ? item.maxlength : 50" />
						<wPicker mode="region" @confirm="addressChange" :ref="'wPicker_'+ item.name" themeColor="#f00">
						</wPicker>
					</view>
					<view v-else-if="item.type=='img'">
						<view v-if="item.value==''" class="uni-uploader__input-box">
							<view class="uni-uploader__input" @tap="chooseImage(item)" @click="chooseImage"></view>
						</view>
						<view v-else>
							<image :src="item.value" style="height:60px;" @click="showImg(item)"></image><br />
							<text class="uni-theme-color" @click="chooseImage(item)">修改</text>
						</view>
					</view>
					<textarea v-else-if="item.type=='textarea'" warp="virtual" class="weui-input uni-input-input"
						:placeholder="item.placeholder" v-model="item.value"
						:maxlength="item.maxlength ? item.maxlength : 4000"
						:style="{'height':(item.height?item.height:'120px')}"></textarea>
					<zEditor v-else-if="item.type=='editor'" :uploadUrl="item.url" :html="item.value" ref="zeditor"
						:placeholder="item.placeholder"></zEditor>
					<input v-else class="weui-input uni-input-input" :placeholder="item.placeholder"
						v-model="item.value" :maxlength="item.maxlength ? item.maxlength : 100"
						:disabled="item.disabled" @input="changeInput(item,index)" />
				</view>
			</view>
		</view>
		<view class="weui-bottom" v-if="!options.noButton">
			<button class="weui-btn weui-btn_primary" @click="moUpdate()" style="width:90%;"
				v-if="formType=='v'">修改</button>
			<button class="weui-btn weui-btn_primary" @click="moSave()" style="width:90%;"
				v-else>{{options.saveText ? options.saveText : "保存"}}</button>
		</view>
	</view>
</template>

<script>
	import wPicker from '@/components/w-picker/w-picker.vue'
	import zEditor from '@/components/z-editor/z-editor.vue'

	var thisWPicker, thisItem;
	export default {
		components: {
			wPicker,
			zEditor
		},
		name: 'forms',
		props: {
			options: {
				type: Object,
				default: () => {
					return {}
				}
			},
			formClass: {
				type: String,
				default: "weui-cells weui-cells__form"
			}
		},
		data() {
			return {
				formType: 'a'
			}
		},
		created() {
			if (this.options.formType) this.formType = this.options.formType;
			this.options.columns.forEach((item, index) => {
				if (item.placeholder == undefined) {
					item.placeholder = "请输入" + item.text;
				}
				if (item.mode == 'mobile') {
					item.isMobile = true;

					item.maxlength = 11;
					console.log(item);
				} else if (item.mode == 'year') {

				}
			});

			if (this.formType == 'a') {
				this.initForms(this.options.default ? this.options.default : {});
			} else {
				this.$common.initAjax({
					url: this.options.viewUrl,
					type: "post",
					success: (res) => {
						if (res.flag == 0 || res.flag == 1000) {
							if (this.options.initCheck) {
								this.options.initCheck(res.data, function() {
									this.initForms(res.data);
								});
							} else {
								if(res.data.age == 0)res.data.age = ''
								this.initForms(res.data);
							}
						}
					}
				});

				// this.$utils.postApi(this.options.viewUrl).then(res => {
				// 	console.log(res);
				// 	if (this.options.initCheck) {
				// 		this.options.initCheck(res.data, function() {
				// 			this.initForms(res.data);
				// 		});
				// 	} else {
				// 		this.initForms(res.data);
				// 	}
				// }).catch(err => {
				// 	console.log(err);
				// 	this.$common.alert("网络故障，请稍后重试。");
				// });
			}
		},
		computed: {

		},
		watch: {
			// "options.columns":{
			// 	handler(newValue, oldValue) {
			// 		console.log(newValue,oldValue);
			// 	},
			// 	deep: true
			// },
			formType: {
				handler(newVal) {
					if (this.title != "") {
						uni.setNavigationBarTitle({
							title: (newVal == 'v' ? "查看" : (newVal == 'u' ? "修改" : "添加")) + this.options.title
						});
					}
				},
				deep: true
			}
		},
		methods: {
			initForms: function(formInfo) {
				var initColumns = () => {
					this.options.columns.forEach((item, index) => {
						for (var key in formInfo) {
							if (key == item.name) {
								item.value = formInfo[key];
								if (item.type == "select") {
									if (item.items) {
										item.items.forEach((selectItem, selectIndex) => {
											if (selectItem.value == item.value) {
												item.selectIndex = selectIndex;
												item.selectText = selectItem.text;
											}
										});
									} else {
										item.selectText = formInfo[key];
									}
								}
								break;
							}
						}
						if (item.value == undefined) {
							item.value = "";
						}

						if (item.placeholder == undefined) {
							item.placeholder = item.placeholder;
						}
						this.$set(this.options.columns, index, item);
					});
				}
				if (this.options.getColumns != undefined) {
					this.options.getColumns(function() {
						initColumns();
					});
				} else {
					initColumns();
				}
			},
			changeInput: function(item, index) {
				if (item.mode == 'mobile') {
					var kong = item.value.match(/ /g);

					if (!this.$filters.isEmpty(kong)) {
						if (kong.length == 1) { 
							item.maxlength = 12;
						} else if (kong.length == 2) {
							item.maxlength = 13;
						}
					} else {
						item.maxlength = 11;
					}

					var len = item.value.length;
					var trimLen = item.value.replace(/\s+/g, "").length;

					if ((len == 3 || len == 8)) {
						item.value = item.value + " ";
					} else if (len == 4 && trimLen == 4) {
						item.value = item.value.substring(0, 3) + " " + item.value.substring(3,
							4);
					} else if (len == 9 && trimLen == 8) {
						item.value = item.value.substring(0, 8) + " " + item.value.substring(8,
							9);
					}
					this.$set(this.options.columns, index, item);
				}
				if (item.change) item.change(item);
			},
			getText: function(item) {
				var text = "";
				if (item && item.items) {
					item.items.forEach(function(vl, index) {
						if (vl.value == item.value) {
							text = vl.text;
							return;
						}
					});
				}
				return text;
			},
			wPickerShow: function(item) {
				thisItem = item;
				for (var key in this.$refs) {
					if (("wPicker_" + item.name) == key) {
						thisWPicker = this.$refs[key][0];
					}
				}
				thisWPicker.show();
			},
			wPickerChange: function(val) {
				thisWPicker.hide();
				thisItem.value = val.result;
			},
			addressChange: function(val) {
				// thisItem.Province = val.checkArr[0];
				// thisItem.City = val.checkArr[1];
				// thisItem.District = val.checkArr[2];
				thisItem.area = val.checkArr[0] + '-' + val.checkArr[1] + '-' + val.checkArr[2];
				thisWPicker.hide();
			},
			clickPicker(item,index){
				if(item.fields=="year"){
					if(item.value==''){
						item.value = "1980";
						item.selectText = "1980";
						this.$set(this.options.columns, index, item);
					}
				}
			},
			selectChange: function(evt, item, index) {
				if (item.items) {
					item.selectText = item.items[evt.target.value].text;
					item.value = item.items[evt.target.value].value;
				} else {
					item.selectText = evt.target.value;
					item.value = evt.target.value;
				}

				this.$set(this.options.columns, index, item);
				if (item.change) item.change(item);
			},
			radioChange: function(evt, item) {
				item.value = evt.detail.value;
			},
			moUpdate: function() {
				this.formType = 'u';
			},
			chooseImage: function(item) {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						var tempImagePath = res.tempFilePaths[0];

						uni.showLoading({
							title: "上传中..."
						});
						uni.uploadFile({
							url: item.url, //仅为示例，非真实的接口地址
							filePath: tempImagePath,
							name: 'file',
							formData: {
								'user': 'test'
							},
							success: (uploadFileRes) => {
								if (uploadFileRes.statusCode == 200) {
									var res = JSON.parse(uploadFileRes.data);
									if (res.flag == 0) {
										item.value = res.data.FileUrl;
									} else {
										this.$common.alert(res.result);
									}
								}
							},
							complete: () => {
								uni.hideLoading();
							}
						});
					}
				});
			},
			showImg: function(item) {
				uni.previewImage({
					indicator: "indicator",
					current: 0,
					urls: [item.value]
				});
			},
			moSave: function() {
				var th = this;
				this.options.columns.forEach(function(item, index) {
					if (item.type == "editor") {
						th.$refs.zeditor[0].getHtml(function(html) {
							item.value = th.$common.replaceAll(html, '"', "'");
						});
					}
					// if (item.m == "editor") {
					// 	th.$refs.zeditor[0].getHtml(function(html) {
					// 		item.value = th.$common.replaceAll(html, '"', "'");
					// 	});
					// }
				});
				var formInfo = this.$common.checkForms(this.options.columns);

				if (typeof formInfo == "object") {
					var addData = function() {
						formInfo.EditType = th.formType;
						if (formInfo.tell != "" && formInfo.tell != undefined && formInfo.tell != null) {
							formInfo.tell = formInfo.tell.replace(/\s+/g, "");
						}
						th.$utils.postApi(th.options.saveUrl, formInfo).then(res => {
							console.log(res);
							if (res.code == 0) {
								var addOptions = res.data;
								console.log(addOptions);
								th.$common.toast("保存成功");
								th.$common.back();
							} else {
								console.log(res);
								th.$common.toast("保存失败");
							}
						}).catch(err => {
							console.error(err);
							th.$common.alert("网络故障，请稍后重试。");
						})
					}

					if (th.options.saveCheck) {
						if (th.options.saveCheck(formInfo)) {
							addData();
						}
					} else {
						addData();
					}
				}
			}
		}
	}
</script>

<style lang="scss">
	.v-textarea {
		white-space: pre-wrap;
		word-wrap: break-word;
		word-break: break-all;
	}
</style>
